<!DOCTYPE html>
<html lang="zh" xml:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>自定义调试 - 物联网调试管理系统</title>
    <script th:src="@{/statics/jquery-1.12.4.min.js}"></script>
    <script th:src="@{/statics/tabler/tabler.min.js}"></script>
    <link rel="stylesheet" th:href="@{/statics/tabler/tabler.min.css}">
    <link rel="stylesheet" th:href="@{/statics/system/common.css}">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>
    <script th:src="@{/statics/system/common.js}"></script>
</head>
<body>
<div class="page">
    <div th:replace="common/header :: header"></div>

    <div class="page-wrapper">
        <div class="page-header d-print-none">
            <div class="container-xl">
                <div class="row g-2 align-items-center">
                    <div class="col">
                        <!-- Page pre-title -->
                        <div class="page-pretitle">
                            物联网调试管理后台
                        </div>
                        <h2 class="page-title">
                            自定义调试
                        </h2>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="page-body">
        <div class="container-xl">
            <div class="row">
                <div class="col-12">
                    <div class="alert alert-success" role="alert" style="text-align: center;">
                        <h4 style="margin-bottom: 0;">连接状态：<span id="status" style="color: red;">断开</span></h4>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-7">
                    <div class="input-group mb-3">
                        <span class="input-group-text">服务器</span>
                        <input type="text" class="form-control" id="server" required>
                    </div>
                </div>
                <div class="col-5">
                    <div class="input-group mb-3">
                        <span class="input-group-text">端口</span>
                        <input type="text" class="form-control" id="port" required>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-6">
                    <div class="input-group mb-3">
                        <span class="input-group-text">用户名</span>
                        <input type="text" class="form-control" id="username">
                    </div>
                </div>
                <div class="col-6">
                    <div class="input-group mb-3">
                        <span class="input-group-text">密码</span>
                        <input type="password" class="form-control" id="password">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-12">
                    <div class="input-group mb-3">
                        <span class="input-group-text">Client ID</span>
                        <input type="text" class="form-control" id="clientid" required>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-12">
                    <div class="input-group mb-3">
                        <span class="input-group-text">订阅主题</span>
                        <input type="text" class="form-control" id="topic" required>
                    </div>
                </div>
            </div>
            <div class="row" style="margin-bottom: 10px;">
                <div class="col-6">
                    <div class="input-group">
                        <textarea class="form-control" id="system-log" style="height: 100%;color:darkgray;font-size: 14px;" readonly></textarea>
                    </div>
                </div>
                <div class="col-6">
                    <div class="card">
                        <div class="card-body" id="connectCard">
                            <p class="card-text">重新填写连接信息后，重新点击下方的"连接"按钮即可连接。</p>
                            <button type="button" class="btn btn-primary" style="margin: 0 auto;" id="connect">连接</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-12">
                    <div class="input-group mb-3">
                        <span class="input-group-text">消息内容</span>
                        <input id="sendMessage" type="text" class="form-control" required>
                    </div>
                    <div class="input-group mb-3">
                        <span class="input-group-text">发送主题</span>
                        <input id="sendTopic" type="text" class="form-control" required>
                        <button class="btn btn-primary" type="button" id="sendButton">发送消息</button>
                    </div>

                </div>
            </div>
            <div class="row">
                <div class="col-12">
                    <div class="input-group">
                    <textarea class="form-control" id="message"
                              style="min-height: 500px;max-height: 500px;color:darkgray;font-size: 14px;" readonly></textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<style>

</style>

<script>
    let client;
    $(function(){
        //随机生成Client ID
        var clientid = "MQTTWeb_" + Math.random().toString(16).substr(2, 8);
        $("#clientid").val(clientid);

        //临时设置几个默认值
        $("#server").val("sflr.nicholasld.cn");
        $("#port").val("8083");
        $("#username").val("");
        $("#password").val("");
        $("#topic").val("/suye/mqtt");
        $("#sendTopic").val("/suye/mqtt");

        //菜单class追加属性
        $(function () {
            $("#custom_mqtt").addClass("active");
        });
    })

    var textarea = document.getElementById("system-log");
    var div = document.getElementsByClassName("card-body")[0];
    textarea.style.height = div.offsetHeight + "px";
    textarea.style.maxHeight = div.offsetHeight + "px";
    textarea.style.minHeight = div.offsetHeight + "px";
    window.addEventListener("resize", function () {
        textarea.style.height = div.offsetHeight + "px";
        textarea.style.maxHeight = div.offsetHeight + "px";
        textarea.style.minHeight = div.offsetHeight + "px";
    });

    $("#connect").click(function () {
        if (client == null) {
            connect();
        }

        if (client.isConnected()) {
            unconnect();
            connect();
        }
    });

    //连接
    function connect() {
        if (!validateConnection()) {
            return;
        }
        var server = $("#server").val();
        var port = $("#port").val();
        var username = $("#username").val();
        var password = $("#password").val();
        var clientid = $("#clientid").val();
        var topic = $("#topic").val();
        var options = {
            timeout: 3,
            //Gets Called if the connection has sucessfully been established
            onSuccess: function () {
                console.log("连接成功");
                $('#system-log').val(
                    '[' + new Date().toLocaleString() + '] '
                    + '[SERVER] '
                    + '服务器连接成功！' + '\n'
                    + $('#system-log').val()
                );
                $('#status').text('已连接');
                client.subscribe(topic);
                $('#system-log').val(
                    '[' + new Date().toLocaleString() + '] '
                    + '[SUBSCRIBE] '
                    + '频道订阅成功：' + topic
                    + '\n'
                    + $('#system-log').val()
                );
            },
            //Gets Called if the connection could not be established
            onFailure: function (message) {
                console.log("连接失败");
                $('#system-log').val(
                    '[' + new Date().toLocaleString() + '] '
                    + '[SERVER] '
                    + '服务器失败，错误' + message.errorMessage
                    + '\n'
                    + $('#system-log').val()
                );
            }
        };
        //设置连接信息
        if (username != "") {
            options.userName = username;
        }
        if (password != "") {
            options.password = password;
        }
        //创建客户端实例
        client = new Paho.MQTT.Client(server, Number(port), clientid);
        //设置回调函数
        client.onConnectionLost = onConnectionLost;
        client.onMessageArrived = onMessageArrived;
        //连接服务器并注册连接选项
        client.connect(options);
    }

    function unconnect() {
        if(client.isConnected()){
            client.disconnect();
            $('#status').text('未连接');
            $('#system-log').val(
                '[' + new Date().toLocaleString() + '] '
                + '[SERVER] '
                + '服务器断开连接。' + '\n'
                + $('#system-log').val()
            );
            console.log("断开成功");
        }
    }

    //连接丢失回调函数
    function onConnectionLost(responseObject) {
        if (responseObject.errorCode !== 0) {
            console.log("连接丢失：" + responseObject.errorMessage);
            $('#status').text('未连接');
            $('#system-log').val(
                '[' + new Date().toLocaleString() + '] '
                + '[SERVER] '
                + '服务器连接丢失！' + '\n'
                + $('#system-log').val()
            );
        }
    }

    //消息到达回调函数
    function onMessageArrived(message) {
        console.log("收到消息：" + message.payloadString);
        $("#message").val(
            '['+ new Date().toLocaleString()+'] '
            + '[接收] '
            + "[" + message.destinationName + "] "
            + message.payloadString
            + "\n"
            + $("#message").val()
        );
    }

    //验证连接信息完整性
    function validateConnection() {
        var server = $("#server").val();
        var port = $("#port").val();
        var clientid = $("#clientid").val();
        var topic = $("#topic").val();
        if (server == "" || port == "" || clientid == "" || topic == "") {
            alert("请填写完整的连接信息！");
            return false;
        }
        return true;
    }

    //发送消息
    $("#sendButton").click(function () {
        if (client == null) {
            alert("请先连接服务器！");
            return;
        }
        if (!client.isConnected()) {
            alert("请先连接服务器！");
            return;
        }
        var topic = $("#sendTopic").val();
        var message = $("#sendMessage").val();
        console.log("发送消息：" + message);
        console.log("订阅：" + topic);
        if (topic === "" || message === "") {
            alert("请填写完整的消息信息！");
            return;
        }
        client.send(topic,message);
        $("#message").val(
            '['+ new Date().toLocaleString()+'] '
            + '[发送] '
            + "[" + topic + "] "
            + message
            + "\n"
            + $("#message").val()
        );
    });
</script>
</html>
